package com.pratices.requestAndResponse.servlet;

import com.pratices.requestAndResponse.bean.CskaoyanLog;
import com.pratices.requestAndResponse.mapper.CskaoyanLogMapper;
import com.pratices.requestAndResponse.mapper.LoginUserMapper;
import com.pratices.requestAndResponse.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/1")
public class DefaultServlet extends HttpServlet {



    static CskaoyanLogMapper cskaoyanLogMapper;
    static CskaoyanLog cskaoyanLog =  new CskaoyanLog();

    static SqlSession sqlSession;
    static {
        sqlSession = MybatisUtils.getSqlConnection();
        cskaoyanLogMapper = sqlSession.getMapper(CskaoyanLogMapper.class);
    }



    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("utf-8");
        System.out.println("请求到达 DefaultServlet！URI: " + request.getRequestURI());
        //获取操作URL
        String operation = request.getRequestURI();
        //获取客户端IPV4地址
        String ip = getClientIPv4(request);
        System.out.println("ip = " + ip);
        //获取请求时间
        // 获取请求时间
        long dateHeader = request.getDateHeader("date");
        String add_time;
        if (dateHeader != -1) {
            // 如果有有效的日期头，格式化为数据库接受的格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            add_time = sdf.format(new Date(dateHeader));
        } else {
            // 如果没有日期头，使用当前时间
            add_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        }
        //放入
        cskaoyanLog.setOperation(operation);
        cskaoyanLog.setIp(ip);
        cskaoyanLog.setAdd_time(add_time);
        //插入数据库
        int insertCskaoyanLog = cskaoyanLogMapper.insertCskaoyanLog(cskaoyanLog);
        if (insertCskaoyanLog > 0) {
            //返回成功
            response.getWriter().write("{\"code\":200,\"msg\":\"success\"}");
        } else {
            //返回失败
            response.getWriter().write("{\"code\":500,\"msg\":\"fail\"}");
        }
    }
    public static String getClientIPv4(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 处理IPv6本地地址
        if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("::1")) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = "127.0.0.1";
            }
        }

        // 可能有多个IP的情况（通过代理）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return ip;
    }
}
